package com.sskj.protocol.sskjboard;

import com.sskj.common.dto.DeviceTelemetry;
import com.sskj.common.dto.EncodedCommand;
import com.sskj.common.vo.req.DeviceCommandReq;
import com.sskj.protocol.IProtocol;
import com.sskj.protocol.annotation.CommunicationProtocol;
import com.sskj.protocol.sskjboard.handler.CommandHandler;
import com.sskj.protocol.sskjboard.handler.FrameMessageHandler;
import com.sskj.protocol.sskjboard.model.FrameMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Component
@CommunicationProtocol(name = "三思主板", code = "sskj_board", description = "三思主板通信协议")
public class SSKJBoardProtocol implements IProtocol {

    @Autowired
    private FrameMessageHandler frameMessageHandler;

    @Autowired
    private CommandHandler commandHandler;

    @Override
    public EncodedCommand encode(DeviceCommandReq command) {
        return commandHandler.handler(command);
    }

    @Override
    public DeviceTelemetry decode(byte[] data) throws IOException {
        ByteBuf byteBuf = Unpooled.wrappedBuffer(data);
        try {
            byte commandCode = byteBuf.readByte();
            byte commandType = byteBuf.readByte();
            int dataLength = byteBuf.readUnsignedShortLE();

            byte[] payload;
            if (dataLength == 0) {
                payload = new byte[0];
            } else {
                payload = new byte[dataLength];
                byteBuf.readBytes(payload);
            }
            // 封装 FrameMessage
            FrameMessage frameMessage = new FrameMessage();
            frameMessage.setCommandCode(commandCode);
            frameMessage.setCommandType(commandType);
            frameMessage.setData(payload);

            return frameMessageHandler.handler(frameMessage);
        } finally {
            byteBuf.release();
        }
    }


}
